import { defineComponent, ref, computed, watch } from 'vue'
import Pager from './pager.jsx' // 导入 Pager 组件
import VeSelect from 'amtf/components/select'
import VeIcon from 'amtf/components/icon'
import { COMPS_NAME, EMIT_EVENTS, LOCALE_COMP_NAME } from './util/constant'
import { clsName } from './util'
import { ICON_NAMES } from 'amtf/constants'
import {是浏览器环境否} from 'amtf/utils';


export default defineComponent({
  name: COMPS_NAME.VE_PAGINATION,

  components: {
    Total: {
      props: ['total'],
      setup(props) {
        return () => (
          <span class={clsName('total')}>{t('total', props.total)}</span>
        )
      },
    },
    Prev: {
      props: ['newPageIndex', 'pageCount'],
      setup(props, { attrs }) {
        return () => (
          <li
            onClick={attrs.prevPage}
            class={[
              props.newPageIndex === 1 ? clsName('disabled') : '',
              clsName('li'),
              clsName('prev'),
            ]}
          >
            <a>
              <VeIcon name={ICON_NAMES.LEFT_ARROW} />
            </a>
          </li>
        )
      },
    },
    Pager,
    Next: {
      props: ['newPageIndex', 'pageCount'],
      setup(props, { attrs }) {
        return () => (
          <li
            onClick={attrs.nextPage}
            class={[
              props.newPageIndex === props.pageCount ? clsName('disabled') : '',
              clsName('li'),
              clsName('next'),
            ]}
          >
            <a>
              <VeIcon name={ICON_NAMES.RIGHT_ARROW} />
            </a>
          </li>
        )
      },
    },
    Sizer: {
      props: ['newPageSize', 'newPageSizeOption', 'popperAppendTo'],
      setup(props, { emit }) {
        const handleChange = (items) => {
          if (Array.isArray(items) && items.length > 0) {
            let item = items.find((x) => x.selected)
            if (item) {
              emit('pageSizeChangeHandler', item.value)
            }
          }
        }

        return () => (
          <VeSelect
            class={clsName('select')}
            value={props.newPageSize}
            options={props.newPageSizeOption}
            popperAppendTo={props.popperAppendTo}
            onInput={handleChange}
          />
        )
      },
    },
    Jumper: {
      props: ['newPageIndex', 'getValidNum'],
      setup(props, { attrs }) {
        const jumperEnter = (event) => {
          if (event.keyCode !== 13) return

          var val = attrs.getValidNum(event.target.value)
          event.target.value = val
          attrs.jumpPageHandler(val)
        }

        return () => (
          <span class={clsName('goto')}>
            &nbsp;{t('goto')}&nbsp;
            <input
              class={clsName('goto-input')}
              type="text"
              onKeyup={jumperEnter}
            />
            &nbsp;{t('page')}&nbsp;
          </span>
        )
      },
    },
  },

  props: {
    layout: {
      type: Array,
      default: () => ['total', 'prev', 'pager', 'next', 'sizer', 'jumper'],
    },
    total: {
      type: Number,
      required: true,
    },
    pageIndex: {
      type: Number,
      default: 1,
    },
    pagingCount: {
      type: Number,
      default: 5,
    },
    pageSize: {
      type: Number,
      default: 10,
    },
    pageSizeOption: {
      type: Array,
      default: () => [10, 20, 30],
    },
    popperAppendTo: {
     type: [String, 是浏览器环境否 ? HTMLElement : Object],
      default: () => document.body,
    },
  },

  setup(props, { emit }) {
    const newPageIndex = ref(
      props.pageIndex && props.pageIndex > 0 ? parseInt(props.pageIndex) : 1
    )
    const newPageSize = ref(props.pageSize)

    const pageCount = computed(() => Math.ceil(props.total / newPageSize.value))
    const newPageSizeOption = computed(() =>
      props.pageSizeOption.map((size) => ({
        value: size,
        label: `${size} ${t('itemsPerPage')}`,
        selected: newPageSize.value === size,
      }))
    )

    watch(
      () => props.pageIndex,
      (newVal) => {
        newPageIndex.value = newVal
      }
    )

    watch(
      () => props.pageSize,
      (newVal) => {
        newPageSize.value = newVal
      }
    )

    const getValidNum = (value) => {
      let result = 1
      value = parseInt(value, 10)

      if (isNaN(value) || value < 1) {
        result = 1
      } else {
        if (value > pageCount.value) {
          result = pageCount.value
        } else {
          result = value
        }
      }
      return result
    }

    const jumpPageHandler = (newPageIndex) => {
      newPageIndex = getValidNum(newPageIndex)
      newPageIndex.value = newPageIndex
      emit(EMIT_EVENTS.PAGE_NUMBER_CHANGE, newPageIndex.value)
    }

    const prevPage = () => {
      if (newPageIndex.value > 1) {
        newPageIndex.value -= 1
        emit(EMIT_EVENTS.PAGE_NUMBER_CHANGE, newPageIndex.value)
      }
    }

    const nextPage = () => {
      if (newPageIndex.value < pageCount.value) {
        newPageIndex.value += 1
        emit(EMIT_EVENTS.PAGE_NUMBER_CHANGE, newPageIndex.value)
      }
    }

    const resetToInitialPageIndex = () => {
      newPageIndex.value =
        props.pageIndex && props.pageIndex > 0 ? parseInt(props.pageIndex) : 1
    }

    const resetToInitialPageSize = () => {
      if (props.pageSize > 0) {
        newPageSize.value = props.pageSize
      }
    }

    const template = <ul class="ve-pagination"></ul>

    const comps = {
      total: <Total total={this.total} />,
      prev: (
        <Prev
          newPageIndex={this.newPageIndex}
          pageCount={this.pageCount}
          prevPage={this.prevPage}
        />
      ),
      pager: (
        <Pager
          pageCount={this.pageCount}
          pageIndex={this.newPageIndex}
          pagingCount={this.pagingCount}
          jumpPageHandler={this.jumpPageHandler}
        />
      ),
      next: (
        <Next
          newPageIndex={this.newPageIndex}
          pageCount={this.pageCount}
          nextPage={this.nextPage}
        />
      ),
      sizer: (
        <Sizer
          newPageSize={this.newPageSize}
          newPageSizeOption={this.newPageSizeOption}
          popperAppendTo={this.popperAppendTo}
          onPageSizeChangeHandler={this.pageSizeChangeHandler}
        />
      ),
      jumper: (
        <Jumper
          newPageIndex={this.newPageIndex}
          getValidNum={this.getValidNum}
          onJumpPageHandler={this.jumpPageHandler}
        />
      ),
    }

    this.layout.forEach((item) => {
      if (comps[item]) template.children.push(comps[item])
    })

    return template
    // return () => (
    //   <ul class="ve-pagination">
    //     {props.layout.includes('total') && <Total total={props.total} />}
    //     {props.layout.includes('prev') && (
    //       <Prev
    //         newPageIndex={newPageIndex.value}
    //         pageCount={pageCount.value}
    //         prevPage={prevPage}
    //       />
    //     )}
    //     {props.layout.includes('pager') && (
    //       <Pager
    //         pageCount={pageCount.value}
    //         pageIndex={newPageIndex.value}
    //         pagingCount={props.pagingCount}
    //         jumpPageHandler={jumpPageHandler}
    //       />
    //     )}
    //     {props.layout.includes('next') && (
    //       <Next
    //         newPageIndex={newPageIndex.value}
    //         pageCount={pageCount.value}
    //         nextPage={nextPage}
    //       />
    //     )}
    //     {props.layout.includes('sizer') && (
    //       <Sizer
    //         newPageSize={newPageSize.value}
    //         newPageSizeOption={newPageSizeOption.value}
    //         popperAppendTo={props.popperAppendTo}
    //         onPageSizeChangeHandler={pageSizeChangeHandler}
    //       />
    //     )}
    //     {props.layout.includes('jumper') && (
    //       <Jumper
    //         newPageIndex={newPageIndex.value}
    //         getValidNum={getValidNum}
    //         onJumpPageHandler={jumpPageHandler}
    //       />
    //     )}
    //   </ul>
    // );
  },
})
